<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async函数的实现原理</title>
</head>
<body>
    <h1>async函数的实现原理</h1>
    <h2>async函数就是将Generator函数和自动执行器包装在一个函数里</h2>

    <script>
        // Generator函数的写法
        function* gen() {
            yield 1;
            yield 2;
            return 3;
        }

        // async函数的实现
        function spawn(genF) {
            return new Promise((resolve, reject) => {
                const gen = genF();
                function step(nextF) {
                    let next;
                    try {
                        next = nextF();
                    } catch(e) {
                        return reject(e);
                    }
                    if(next.done) {
                        return resolve(next.value);
                    }
                    Promise.resolve(next.value).then(
                        v => step(() => gen.next(v)),
                        e => step(() => gen.throw(e))
                    );
                }
                step(() => gen.next());
            });
        }

        // 使用示例
        async function chainOperations() {
            try {
                const result1 = await asyncOperation1();
                console.log(result1);
                const result2 = await asyncOperation2(result1);
                console.log(result2);
                return result2;
            } catch (err) {
                console.error('Error:', err);
            }
        }

        // 模拟异步操作
        function asyncOperation1() {
            return new Promise(resolve => 
                setTimeout(() => resolve('第一步'), 1000)
            );
        }

        function asyncOperation2(input) {
            return new Promise(resolve =>
                setTimeout(() => resolve(`${input} -> 第二步`), 1000)
            );
        }

        // 执行
        chainOperations().then(result => {
            console.log('完成:', result);
        });
    </script>
</body>
</html> 